package org.lilei;

import org.reflections.Reflections;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Set;

/**
 * @author lilei
 * @date 2020-04-03
 */
@Configuration
public class SpringConfig implements BeanDefinitionRegistryPostProcessor {
    private static final String SCANNER_PATH = "org.lilei";
    private static final String host = "localhost";
    private static final int port = 8080;

    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
        Reflections reflections = new Reflections(SCANNER_PATH);
        Set<Class<?>> clazzSet = reflections.getTypesAnnotatedWith(RpcClient.class);
        for (Class<?> aClass : clazzSet) {
            BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(RpcClientFactoryBean.class);
            BeanDefinition beanDefinition = beanDefinitionBuilder.getBeanDefinition();

            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(aClass);
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(host);
            beanDefinition.getConstructorArgumentValues().addGenericArgumentValue(port);

            registry.registerBeanDefinition(aClass.getSimpleName(), beanDefinition);
        }
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    }
}
